import { ref, computed } from 'vue'
import { generateSnowflakeId } from '@/utils/snowflakeId.js'

/**
 * 问卷组管理组合式函数
 * 用于管理连续答5个问卷的逻辑
 */
export function useQuestionnaireGroup() {
  // 问卷组ID（雪花ID）
  const userAnswerGroupId = ref('')
  
  // 当前问卷索引 (0-4，共5个问卷)
  const currentQuestionnaireIndex = ref(0)
  
  // 问卷配置
  const questionnaires = ref([
    { id: 2, name: '问卷一', type: '外倾性', completed: false, userAnswerId: null },
    { id: 3, name: '问卷二', type: '宜人性', completed: false, userAnswerId: null },
    { id: 4, name: '问卷三', type: '尽责性', completed: false, userAnswerId: null },
    { id: 5, name: '问卷四', type: '神经质', completed: false, userAnswerId: null },
    { id: 6, name: '问卷五', type: '开放性', completed: false, userAnswerId: null },
  ])
  
  // 当前问卷
  const currentQuestionnaire = computed(() => {
    return questionnaires.value[currentQuestionnaireIndex.value]
  })
  
  // 当前问卷ID
  const currentQuestionnaireId = computed(() => {
    return currentQuestionnaire.value?.id
  })
  
  // 是否所有问卷都已完成
  const isAllCompleted = computed(() => {
    return questionnaires.value.every(q => q.completed)
  })
  
  // 已完成问卷数量
  const completedCount = computed(() => {
    return questionnaires.value.filter(q => q.completed).length
  })
  
  // 进度百分比
  const progressPercentage = computed(() => {
    return Math.round((completedCount.value / questionnaires.value.length) * 100)
  })
  
  // 初始化问卷组
  const initQuestionnaireGroup = () => {
    // 生成雪花ID作为问卷组ID
    userAnswerGroupId.value = generateSnowflakeId()
    
    // 重置所有问卷状态
    questionnaires.value.forEach(q => {
      q.completed = false
      q.userAnswerId = null
    })
    
    // 重置当前问卷索引
    currentQuestionnaireIndex.value = 0
    
    // 保存到sessionStorage
    sessionStorage.setItem('userAnswerGroupId', userAnswerGroupId.value)
    sessionStorage.setItem('currentQuestionnaireIndex', '0')
    sessionStorage.setItem('questionnaires', JSON.stringify(questionnaires.value))
    
    return userAnswerGroupId.value
  }
  
  // 从sessionStorage恢复状态
  const restoreFromStorage = () => {
    const storedGroupId = sessionStorage.getItem('userAnswerGroupId')
    const storedIndex = sessionStorage.getItem('currentQuestionnaireIndex')
    const storedQuestionnaires = sessionStorage.getItem('questionnaires')
    
    if (storedGroupId) {
      userAnswerGroupId.value = storedGroupId
    }
    
    if (storedIndex !== null) {
      currentQuestionnaireIndex.value = parseInt(storedIndex)
    }
    
    if (storedQuestionnaires) {
      questionnaires.value = JSON.parse(storedQuestionnaires)
    }
  }
  
  // 标记当前问卷完成
  const markCurrentCompleted = (userAnswerId) => {
    if (currentQuestionnaire.value) {
      currentQuestionnaire.value.completed = true
      currentQuestionnaire.value.userAnswerId = userAnswerId
      
      // 保存到sessionStorage
      sessionStorage.setItem('questionnaires', JSON.stringify(questionnaires.value))
    }
  }
  
  // 进入下一个问卷
  const nextQuestionnaire = () => {
    if (currentQuestionnaireIndex.value < questionnaires.value.length - 1) {
      currentQuestionnaireIndex.value++
      sessionStorage.setItem('currentQuestionnaireIndex', currentQuestionnaireIndex.value.toString())
      return true
    }
    return false
  }
  
  // 进入上一个问卷
  const prevQuestionnaire = () => {
    if (currentQuestionnaireIndex.value > 0) {
      currentQuestionnaireIndex.value--
      sessionStorage.setItem('currentQuestionnaireIndex', currentQuestionnaireIndex.value.toString())
      return true
    }
    return false
  }
  
  // 跳转到指定问卷
  const goToQuestionnaire = (index) => {
    if (index >= 0 && index < questionnaires.value.length) {
      currentQuestionnaireIndex.value = index
      sessionStorage.setItem('currentQuestionnaireIndex', currentQuestionnaireIndex.value.toString())
      return true
    }
    return false
  }
  
  // 获取问卷结果
  const getQuestionnaireResult = (questionnaireId) => {
    console.log(questionnaires.value);
    const questionnaire = questionnaires.value.find(q => q.id === questionnaireId)
    console.log(questionnaire);
    
    return questionnaire?.userAnswerId || null
  }
  
  // 清除所有状态
  const clearAll = () => {
    sessionStorage.removeItem('userAnswerGroupId')
    sessionStorage.removeItem('currentQuestionnaireIndex')
    sessionStorage.removeItem('questionnaires')
    
    userAnswerGroupId.value = ''
    currentQuestionnaireIndex.value = 0
    questionnaires.value.forEach(q => {
      q.completed = false
      q.userAnswerId = null
    })
  }
  
  return {
    // 响应式数据
    userAnswerGroupId,
    currentQuestionnaireIndex,
    questionnaires,
    
    // 计算属性
    currentQuestionnaire,
    currentQuestionnaireId,
    isAllCompleted,
    completedCount,
    progressPercentage,
    
    // 方法
    initQuestionnaireGroup,
    restoreFromStorage,
    markCurrentCompleted,
    nextQuestionnaire,
    prevQuestionnaire,
    goToQuestionnaire,
    getQuestionnaireResult,
    clearAll
  }
} 